//
//  DDOpenInvoice.swift
//  DingDongZP
//
//  Created by 三秒文化 on 2016/10/17.
//  Copyright © 2016年 51ledian.com. All rights reserved.
//

import UIKit

class DDOpenInvoice: LDBaseCustomizeVC {

    var headerView:DDOpenInvoiceMoneyView?
    var bottomView:LDBottomBtnView?
    
    var tableView:LDBaseTableView?
    
    var model:DDInvoiceInfoModel?
    var listModel:DDInvoiceInfoModelList?
    
    
    private var mMoneyAmount:String?// = "0"
    
    
    //是否有默认抬头
    private var isSelInvoiceInfo = false
    
    private let cellInputID = "cellInputID"
    private let cellDetailID = "cellDetailID"
    private let cellNoDetailID = "cellNoDetailID"
    private let actionBtnStr = "提交开票申请"
    
    private let headerH:CGFloat = 90
    
    override func viewDidLoad() {
        
        super.viewDidLoad()
        
        
        
        tableView = LDBaseTableView.init(frame: view.frame, style: UITableViewStyle.Plain)
        tableView?.contentInset = UIEdgeInsetsMake(LDFrame.TableCellMargin, 0, 0, 0)
        view.addSubview(tableView!)

        tableView?.delegate = self
        tableView?.dataSource = self
        
        headerView = DDOpenInvoiceMoneyView.init(frame: CGRectMake(0, 0, LDFrame.ScreenWidth, headerH))        
        tableView!.tableHeaderView = headerView!
        
        bottomView = LDBottomBtnView.init(frame: CGRectMake(0, 0, LDFrame.ScreenWidth, 80))
        bottomView?.title = actionBtnStr
        tableView!.tableFooterView = bottomView
        
        bottomView?.actionBtn?.rac_signalForControlEvents(UIControlEvents.TouchUpInside).subscribeNext({ [weak self]
            (any) in
            
            let monerStr = self?.model?.invoice_money ?? "0"
            
            
            let preM = Int(monerStr) ?? 0
            if !(self?.mMoneyAmount?.characters.count > 0) {
                
                self?.showLDAlertView("输入金额无效...")
            } else if preM == 0 {
                
                self?.showLDAlertView("可开票金额为零...")
            } else if !(self?.model?.list.count > 0) {
                
                self?.showLDAlertView("请添加抬头信息...")
            } else {
                
                self?.showLDAlertView("请确定提交金额", info: self?.mMoneyAmount ?? "null", sure: {
                    
                    self?.sendInvoiceMoneyAmount()
                    
                }, cancel: {
                        
                        
                })
            }
        })
    }
    
    //
    override func viewWillAppear(animated: Bool) {
        
        requestData()
    }
    
    func updateUI() {
        
        getIsDefaultInvoiceInfo()
        headerView!.mMoneyAmount = model?.invoice_money ?? "0.00"
        getIsDefaultInvoiceInfo()
        tableView?.reloadData()
    }
    
    // has default invoiceinfo ?
    func getIsDefaultInvoiceInfo() {
        
        if model?.list.isEmpty == true {
            
            isSelInvoiceInfo = false
            
        } else {
            
            isSelInvoiceInfo = true
        }
    }
    
    //清空input
    func clearInput() {
        
//        let index = NSIndexPath.init(forRow: 0, inSection: 1)
        let cell = tableView?.visibleCells.first as?DDOpenInvoiceMoneyInput//cellForRowAtIndexPath(index) as? DDOpenInvoiceMoneyInput
        cell?.inputMoneyLab?.text = ""
    }
    
    //请求开票信息抬头
    func requestData() {
        
        
        LDUserInfoNet.sharedInstance.getInvoiceInfo(nil, succ: { [weak self] (dictArr) in
            
            self?.model = DDInvoiceInfoModel.yy_modelWithDictionary(dictArr)
            self?.listModel = self?.model?.list.first //as? DDInvoiceInfoModelList
        
            self?.updateUI()
            
        }) { (err) in
            
        }
    }
    
    //提交数据
    func sendInvoiceMoneyAmount() {
        
        let dict = ["money":mMoneyAmount ?? ""]
        LDUserInfoNet.sharedInstance.submitInvoiceMoneyAmount(listModel?.id.stringValue, params: dict, succ: { [weak self] (str) in
            
            self?.clearInput()
            LDShowHUB.shareInstance.showSucc(str)
            self?.requestData()
        }) { (err) in
            
            LDShowHUB.shareInstance.showErr(err as? String ?? "失败")
        }
    }
    //
}

extension DDOpenInvoice:UITableViewDelegate,UITableViewDataSource {
    

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return 2
    }

    
     func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        
        
        if indexPath.row == 0 {
            
            var cell = tableView.dequeueReusableCellWithIdentifier(cellInputID) as? DDOpenInvoiceMoneyInput
            if cell == nil {
                
                cell = DDOpenInvoiceMoneyInput.init(type: .TopGamp, margin: LDFrame.TableCellMargin, style: .Default, reuseIdentifier: cellInputID)
                cell!.inputMoneyLab?.keyboardType = .NumberPad
            }
            
            cell?.inputMoneyLab?.rac_textSignal().subscribeNext({ [weak self] (text) in
                
                self?.mMoneyAmount = text as? String ?? ""
            })
            
            return cell!
            
        } else {
            
            if isSelInvoiceInfo == true {
                
                var cell = tableView.dequeueReusableCellWithIdentifier(cellDetailID) as? DDInvoiceDetailViewCell
                if cell == nil {
                    
                    cell = DDInvoiceDetailViewCell(topMargin: LDFrame.TableCellMargin,style: .Default, reuseIdentifier: cellDetailID)
                }
                
                cell?.status = true
                
                if listModel != nil {
                    
                    let placeStr = String.init(format: "%@-%@-%@", listModel!.province,listModel!.city,listModel?.dist ?? "")
                    cell?.descLabArr = [listModel!.name,listModel!.link_name,listModel!.link_mobile,placeStr,listModel!.address]
                }
                
                return cell!
                
            } else {
                
                var cell = tableView.dequeueReusableCellWithIdentifier(cellDetailID) as? DDOpenInvoiceMoneyInputNoticeCell
                
                if cell == nil {
                    
                    cell = DDOpenInvoiceMoneyInputNoticeCell(type: .TopGamp, margin: LDFrame.TableCellMargin, style: .Default, reuseIdentifier: cellInputID)
                }
                
                cell?.title = "请添加默认抬头信息"
                return cell!
            }
        }
    }
    
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        
        if indexPath.row == 1 {
            
            let vc = DDInvoiceManagerInfoVC()
            vc.title = "选择默认开票信息"
            navigationController?.pushViewController(vc, animated: false)
        }
    }
    
    func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        
        if indexPath.row == 0 || isSelInvoiceInfo == false{
            
            return 80
        } else {
            
            return 270
        }
    }
    
    func scrollViewWillBeginDragging(scrollView: UIScrollView) {
        
        registerKeyboard()
    }
}
